<template>
  <view class="page-wrapper">
    <nav-bar title="扫码"></nav-bar>

    <!-- 主体显示区域 -->
    <view class="page-main">
      <div class="scanBox" ref="scanBox">
        <div id="scanarea" class="qrarea"></div>
        <div class="closeId scanBtn" @click="closePage">关闭扫码</div>
        <!-- <div class="lineDiv" style="bottom: 80px"></div>
        <div class="selectqrcode scanBtn">从相册选择二维码</div> -->
      </div>
    </view>
  </view>
</template>

<script setup>
// import { ref, onMounted, onBeforeUnmount, reactive } from 'vue';
import utils from '@/common/js/utils/index.js';

const scanBox = ref(null);

const info = reactive({
  scanInstance_1: null,
});

const closePage = () => {
  uni.navigateBack({
    delta: 1, // 返回到上一个页面
  });
};

const closeScan = () => {
  if (info.scanInstance_1) {
    info.scanInstance_1.close();
    info.scanInstance_1 = null;
  }
};

const errorCallback = (error) => {
  uni.showToast({
    title: '扫码失败，请重试',
    icon: 'error',
  });
  uni.navigateBack({
    delta: 1, // 返回到上一个页面
  });
};

const plusScan = () => {
  let scan = null;
  //扫码成功回调
  function onmarked(type, result) {
    scan.close(); //结束视频捕获

    uni.navigateBack({
      delta: 1, // 返回到上一个页面
      success: () => {
        eventChannel.emit('scansuccess', {
          from: 'plusscan',
          msg: {
            type,
            result,
          },
        });
      },
    });
  }

  try {
    var filter = [plus.barcode.QR];
    //自定义的扫描控件样式
    var styles = {
      top: '0px',
      left: '0px',
      width: '100%',
      height: '100%',
      position: 'static',

      frameColor: '#ffffff',
      scanbarColor: '#ffffff',
      background: '',
    };
    info.scanInstance_1 = new plus.barcode.Barcode(
      'scanarea',
      filter,
      styles,
      true
    );
    info.scanInstance_1.onmarked = onmarked;
    info.scanInstance_1.onerror = errorCallback;
    info.scanInstance_1.start(); //开始扫码
  } catch (err) {
    errorCallback(); // 返回上一个页面并关闭
  }
};

onMounted(() => {
  plusScan();
});

onBeforeUnmount(() => {
  closeScan();
});
</script>

<style lang="scss" scoped>
.scanBox {
  position: absolute;
  z-index: 99999999;
  top: 0px;
  left: 0;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  // padding-bottom: 150px;
  padding-bottom: 80px;
  background: rgba(0, 0, 0, 1);
}
.qrarea {
  width: 100%;
  height: 100%;
  margin: auto;
}
.scanBtn {
  width: 100%;
  position: absolute;
  z-index: 5;
  bottom: 0;
  left: 0;
  color: #ffffff;
  text-align: center;
  height: 80px;
  line-height: 80px;
}
.lineDiv {
  width: 50%;
  position: absolute;
  z-index: 5;
  bottom: 0;
  left: 25%;
  height: 1px;
  background: linear-gradient(
    to right,
    rgba(255, 255, 255, 0) 0,
    rgba(255, 255, 255, 1) 50%,
    rgba(255, 255, 255, 0) 100%
  );
}
.closeId {
  // bottom: 80px;
  bottom: 0px;
}
</style>
